﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DriveBeamEditor.Controls.BeamNG.VehiclePartConfig;
using DriveBeamEditor.Controls.General;
using JBeamLibrary;
using JBeamLibrary.Tools;
using JBeamLibrary.VehicleParts.Elements;
using JBeamLibrary.VehicleParts.Enums;

namespace DriveBeamEditor.Controls.BeamNG.SectionControls
{
    public partial class ThrustersControl : VehiclePartControl
    {
        #region Properties

        private ElementPropertyUse PropertyUse
        {
            get { return rbGroupProp.Checked ? ElementPropertyUse.Group : ElementPropertyUse.Single; }
        }

        #endregion

        #region CTORs

        public ThrustersControl()
        {
            InitializeComponent();
        }

        #endregion

        #region Events

        #region Overrides

        #endregion

        #region Binding source

        private void bindingSourceThrusters_AddingNew(object sender, AddingNewEventArgs e)
        {
            if (DesignMode || VehiclePart == null)
            {
                e.NewObject = new Thruster();
                return;
            }

            /* Avoid loop */
            if (e.NewObject is Beam) return;

            /* Not enough nodes, do not allow */
            if (Vehicle.TotalNodeCount < 2)
            {
                MessageBox.Show(this,
                    @"The selected vehicle doesn't have enough nodes to create a thruster. It requires a minimum of 2 nodes.",
                    @"Not enough nodes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                bindingSourceThrusters.CancelEdit();
                grid.NotifyCurrentCellDirty(true);
                grid.CancelEdit();
                grid.NotifyCurrentCellDirty(false);
                return;
            }

            /* Create new beam */
            e.NewObject = new Thruster(
                VehiclePart.NodeSection[0].Id,
                VehiclePart.NodeSection[1].Id
            );
        }

        private void bindingSourceThrusters_CurrentChanged(object sender, EventArgs e)
        {
            /* No vehicle part loaded */
            if (VehiclePart == null) return;

            /* Update property box title */
            boxThrusterProperties.Text =
                bindingSourceThrusters.Position >= 0 && VehiclePart.ThrusterSection.Count > 0
                ? string.Format("Thruster '{0}' properties", VehiclePart.ThrusterSection[bindingSourceThrusters.Position])
                : @"Thruster properties";

            /* Display properties */
            UpdateProperties(bindingSourceThrusters.Position);
        }

        #endregion

        #region Data grid view

        private void grid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            /* Clicks on headers */
            if (e.ColumnIndex < 0 || e.RowIndex < 0) return;

            //grid_CellContentClick(sender, e);
        }

        private void grid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            /* Clicks on headers */
            if (e.ColumnIndex < 0 || e.RowIndex < 0) return;

            /* Get column & row & cell */
            var col = grid.Columns[e.ColumnIndex];
            var row = grid.Rows[e.RowIndex];

            /* Validate new row */
            if (row.IsNewRow && col == columnDelete)
            {
                bindingSourceThrusters.EndEdit();
                grid.NotifyCurrentCellDirty(true);
                grid.EndEdit();
                grid.NotifyCurrentCellDirty(false);
            }

            /* Select a node for the current cell */
            else if (col != columnDelete)
            {
                if (Config.SelectNodesFromFromCurrentPartOnly)
                    pddNodeSelection.Show(grid, grid.PointToClient(Cursor.Position));
                else
                    pddNodeSelectionFull.Show(grid, grid.PointToClient(Cursor.Position));
            }

            /* Delete the current row */
            else if (col == columnDelete)
            {
                grid.Rows.RemoveAt(e.RowIndex);
            }
        }

        #endregion

        #region Property controls

        private void kvcEditor_EditValueChanged(object sender, EventArgs e)
        {
            /* Get editor */
            var editor = sender as KeyValueControl;
            if (editor == null) return;

            /* Set the property value */
            var properties = VehiclePart.ThrusterSection.Properties;
            var index = bindingSourceThrusters.Position;
            properties.SetPropertyValue(index, editor.Key, PropertyUse, editor.EditValue);
        }

        private void kvcEditor_Validated(object sender, EventArgs e)
        {
            /* Get editor */
            var editor = sender as KeyValueControl;
            if (editor == null) return;

            /* Get index */
            var index = bindingSourceThrusters.Position;

            /* Update related properties (with the same key) */
            if (VehiclePart != null)
                UpdateRelatedProperties(index, editor.Key);
        }

        #endregion

        #region Radio buttons

        private void rbGroupProp_CheckedChanged(object sender, EventArgs e)
        {
            if (rbGroupProp.Checked)
                OnPropertyUseChanged();
        }

        private void rbInlineProp_CheckedChanged(object sender, EventArgs e)
        {
            if (rbInlineProp.Checked)
                OnPropertyUseChanged();
        }

        #endregion

        #region Popups

        private void pcNodeSelection_SelectedNodeChanged(object sender, Node e)
        {
            if (grid.CurrentRow == null || grid.CurrentCell == null || e == null) return;

            var thruster = grid.CurrentRow.DataBoundItem as Thruster;
            if (thruster == null) return;

            var col = grid.Columns[grid.CurrentCell.ColumnIndex];
            if (col == null) return;

            if (col.DataPropertyName.Equals("NodeId1"))
                thruster.NodeId1 = e.Id;
            else if (col.DataPropertyName.Equals("NodeId2"))
                thruster.NodeId2 = e.Id;
        }

        #endregion

        #endregion

        #region Methods

        public override string ToString()
        {
            return "Thrusters";
        }

        private void BindThrusters()
        {
            bindingSourceThrusters.DataSource = null;

            if (VehiclePart != null)
                bindingSourceThrusters.DataSource = VehiclePart.ThrusterSection.ElementCollection;

            grid.Refresh();
        }

        protected override void OnVehiclePartChanged()
        {
            pcNodeSelection.VehiclePart = VehiclePart;
            pcNodeSelectionFull.Vehicle = VehiclePart != null ? VehiclePart.File.Parent : null;

            BindThrusters();
            base.OnVehiclePartChanged();
        }

        private void OnPropertyUseChanged()
        {
            UpdateProperties(bindingSourceThrusters.Position);
        }

        private void UpdateProperties(int index)
        {
            foreach (var editor in
                from Control panel in boxThrusterProperties.Controls
                from box in panel.Controls.OfType<DockGroupBox>()
                from editor in box.Controls.OfType<KeyValueControl>()
                select editor
            )
            {
                var val = GroupHelper.GetPropertyValue(VehiclePart.ThrusterSection, index, editor.Key, PropertyUse);
                editor.SetEditValueSilent(val);
            }
        }

        private void UpdateRelatedProperties(int index, string propName)
        {
            foreach (var editor in
                from Control panel in boxThrusterProperties.Controls
                from box in panel.Controls.OfType<DockGroupBox>()
                from editor in box.Controls.OfType<KeyValueControl>()
                where editor.Key.Equals(propName)
                select editor
            )
            {
                var val = GroupHelper.GetPropertyValue(VehiclePart.ThrusterSection, index, propName, PropertyUse);
                editor.SetEditValueSilent(val);
            }
        }

        #endregion
    }
}
